import { defineStore } from "pinia";
import { ref, computed } from "vue";
import type { User } from "../types";

export const useAuthStore = defineStore("auth", () => {
    // State
    const user = ref<User | null>(null);
    const token = ref<string | null>(localStorage.getItem("auth_token"));
    const isLoading = ref(false);

    // Initialize user from localStorage
    const initializeUser = () => {
        const savedUser = localStorage.getItem("auth_user");
        if (savedUser && token.value) {
            try {
                user.value = JSON.parse(savedUser);
            } catch (error) {
                console.error("Error parsing saved user:", error);
                localStorage.removeItem("auth_user");
                localStorage.removeItem("auth_token");
            }
        }
    };

    // Initialize on store creation
    initializeUser();

    // Getters
    const isAuthenticated = computed(() => !!user.value && !!token.value);
    const userDisplayName = computed(() => user.value?.name || "Guest");

    // Actions
    const login = async (email: string, password: string) => {
        isLoading.value = true;
        try {
            // TODO: Implement actual API call
            // const response = await authApi.login(email, password)

            // Mock login for now
            const mockUser: User = {
                id: "1",
                email,
                name: "张小明",
                avatar: "https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=150&h=150&fit=crop&crop=face",
                preferences: {
                    theme: "dark",
                    language: "zh-CN",
                    notifications: true,
                },
                subscription: {
                    plan: "pro",
                    expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 days from now
                },
                metadata: {
                    createdAt: new Date(Date.now() - 90 * 24 * 60 * 60 * 1000), // 90 days ago
                    lastLoginAt: new Date(),
                    totalSpent: 1250.5,
                },
            };

            user.value = mockUser;
            token.value = "mock_token_" + Date.now();

            // Save to localStorage
            localStorage.setItem("auth_token", token.value);
            localStorage.setItem("auth_user", JSON.stringify(mockUser));

            return { success: true };
        } catch (error) {
            console.error("Login error:", error);
            return { success: false, error: "Login failed" };
        } finally {
            isLoading.value = false;
        }
    };

    const register = async (email: string, password: string, name: string) => {
        isLoading.value = true;
        try {
            // TODO: Implement actual API call
            // const response = await authApi.register(email, password, name)

            // Mock registration for now
            const mockUser: User = {
                id: "1",
                email,
                name,
                avatar: "https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=150&h=150&fit=crop&crop=face",
                preferences: {
                    theme: "dark",
                    language: "zh-CN",
                    notifications: true,
                },
                subscription: {
                    plan: "free",
                },
                metadata: {
                    createdAt: new Date(),
                    lastLoginAt: new Date(),
                    totalSpent: 0,
                },
            };

            user.value = mockUser;
            token.value = "mock_token_" + Date.now();

            // Save to localStorage
            localStorage.setItem("auth_token", token.value);
            localStorage.setItem("auth_user", JSON.stringify(mockUser));

            return { success: true };
        } catch (error) {
            console.error("Registration error:", error);
            return { success: false, error: "Registration failed" };
        } finally {
            isLoading.value = false;
        }
    };

    const logout = () => {
        user.value = null;
        token.value = null;
        localStorage.removeItem("auth_token");
        localStorage.removeItem("auth_user");
    };

    const initializeAuth = () => {
        // Check if user is already logged in
        if (token.value) {
            // TODO: Validate token and fetch user data
            // For now, we'll just check if token exists
        }
    };

    return {
        // State
        user,
        token,
        isLoading,
        // Getters
        isAuthenticated,
        userDisplayName,
        // Actions
        login,
        register,
        logout,
        initializeAuth,
    };
});
